//
//  SerialSelectionViewController.m
//  XPhoto
//
//  Created by baboy on 2019/5/7.
//  Copyright © 2019 baboy. All rights reserved.
//

#import "SerialSearchViewController.h"
#import "BKIndicator.h"
#import "NSThread+x.h"
#import "SerialEditViewController.h"
#import "UIScrollView+x.h"
#import "SerialTableViewCell.h"

@interface SerialSearchViewController ()<UISearchBarDelegate, UISearchResultsUpdating,UITableViewDelegate, UITableViewDataSource,SerialSearchDelegate, SerialEditDelegate, BKScrollViewDragRefreshDelegate>
@property(nonatomic, strong) UISearchController *searchController;
@property(nonatomic, strong) SerialSearchResultsViewController *searchResultsController;
@property(nonatomic, strong) NSMutableArray* serials;
@end

@implementation SerialSearchViewController
- (id)init{
    if (self = [super initWithNibName:NSStringFromClass([self class]) bundle:nil]) {
        _selectedItems = [NSMutableArray array];
        _selectedButtons = [NSMutableArray array];
        _maxSelectedCount = 3;
    }
    return self;
}
- (NSInteger)indexOfSelectedSerial:(PostSerial *)postSerial{
    if (!self.selectedItems) {
        return NO;
    }
    for (NSInteger i = 0, n = self.selectedItems.count; i < n; i++) {
        PostSerial *s = [self.selectedItems objectAtIndex:i];
        if (s.id == postSerial.id) {
            return i;
        }
    }
    return -1;
}
- (UISearchController*)searchController{
    if (!_searchController) {
        _searchResultsController = [[SerialSearchResultsViewController alloc] init];
        _searchResultsController.delegate = self;
        _searchController = [[UISearchController alloc] initWithSearchResultsController:_searchResultsController];
        _searchController.searchResultsUpdater = self;
        
//        _searchController.hidesNavigationBarDuringPresentation = NO;
        _searchController.dimsBackgroundDuringPresentation = NO;
        _searchController.searchBar.placeholder = NSLocalizedString(@"search", @"按钮");
        _searchController.searchBar.delegate = self;
        _searchController.searchBar.returnKeyType = UIReturnKeySearch;
        _searchController.searchBar.showsScopeBar = NO;
    }
    return _searchController;
}
- (void)viewDidLoad {
    [super viewDidLoad];
//    CGRect f = self.tableView.bounds;
//    f.origin.y = - f.size.height;
//
//    UIView *v = [[UIView alloc] initWithFrame:f];
//    v.backgroundColor = [UIColor redColor];
//    self.tableView.contentInset = UIEdgeInsetsMake(100, 0, -100, 0);
//    self.searchController.searchBar.frame = CGRectMake(0, f.size.height-44, self.tableView.bounds.size.width, 44);
//    [v addSubview:self.searchController.searchBar];
    
//    [self.tableView addSubview:v];
    [self.searchController.searchBar sizeToFit];
    self.tableView.tableHeaderView = self.searchController.searchBar;
    [self.searchController.searchBar sizeToFit];
    
    self.definesPresentationContext = YES;
//    [self setAutomaticallyAdjustsScrollViewInsets:YES];
//    [self setExtendedLayoutIncludesOpaqueBars:YES];
    
//    if (@available(iOS 11.0, *)) {
//        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
//    }else {
//        self.automaticallyAdjustsScrollViewInsets = NO;
//    }
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"cancel", @"按钮") style:UIBarButtonItemStylePlain target:self action:@selector(cancel:)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"done", @"按钮") style:UIBarButtonItemStylePlain target:self action:@selector(done:)];
    
    for (NSInteger i = 0, n = self.selectedItems.count; i<n; i++) {
        [self addButtonForSerial:[self.selectedItems objectAtIndex:i]];
    }
    self.tableView.estimatedRowHeight = 80;
    self.tableView.tableFooterView = [UIView new];
    [self search:0];
}
#pragma mark - request
- (void)search:(NSInteger) offset{
    PostSerialSearchArgs *searchArgs = [PostSerialSearchArgs new];
    searchArgs.offset = offset;
    [PostSerial search:searchArgs
          withCallback:^(id  _Nonnull task, id  _Nullable serials, NSError * _Nullable error) {
        if (error) {
            [BKIndicator showMessageAndFadeOut:error.localizedDescription completion:nil];
        }
        if ([serials count] > 0) {
            if (offset == 0) {
                self.serials = [NSMutableArray array];
            }
            [self.serials addObjectsFromArray:serials];
            [self.tableView reloadData];
        }
        if (self.serials.count == 0) {
            UIView *emptyView = [self.tableView showEmptyMsg:NSLocalizedString(@"serial_no_created", @"Serial") icon:nil withTarget:self withAction:nil];
            [self.tableView sendSubviewToBack:emptyView];
        }
        [self.tableView stopLoading];
        self.tableView.loadMore = [serials count] == searchArgs.pageSize;
    }];
}
#pragma buttons
- (void)cancel:(id)button{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
- (void)done:(id)button{
    if (self.selectedItems.count == 0) {
        return;
    }
    if (self.delegate && [self.delegate respondsToSelector:@selector(serialSearchViewController:didSelectSerials:)]) {
        [self.delegate serialSearchViewController:self didSelectSerials:self.selectedItems];
    }
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];    
}
#pragma mark - searchBar

//- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
//    [UIView animateWithDuration:0.1
//                     animations:^{
//         [self.tableView setContentInset:UIEdgeInsetsZero];
//    }];
//    return YES;
//}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    DLOG(@"search:%@", searchText);
    self.searchResultsController.keyword = searchText;
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [self.searchController.searchBar resignFirstResponder];
//    [self.tableView setContentInset:UIEdgeInsetsZero];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    [self.searchController.searchBar resignFirstResponder];
}
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
//    self.edgesForExtendedLayout = UIRectEdgeNone;
}

#pragma mark - UITableView Delegate
- (SerialTableViewCell *)serialTableViewCell{
    SerialTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier: SERIAL_TABLE_VIEW_CELL_REUSE_ID];
    if (!cell) {
        cell = loadViewFromNib([SerialTableViewCell class], self);
    }
    return cell;
}
#pragma UITableViewDelegate Serial Delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSInteger n = self.serials? self.serials.count : 0;
    return n;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    PostSerial *postSerial = [self.serials objectAtIndex:indexPath.row];
    CGFloat h = [[self serialTableViewCell] heightWithPostSerial:postSerial width:tableView.bounds.size.width];
    return h;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    PostSerial *postSerial = [self.serials objectAtIndex:indexPath.row];
    SerialTableViewCell *cell = [self serialTableViewCell];
    cell.postSerial = postSerial;
    BOOL isSelected = [self indexOfSelectedSerial:postSerial] >= 0;
    if (isSelected) {
        cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image"]];
    }
    if (!isSelected) {
        cell.accessoryView = nil;
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    PostSerial *postSerial = [self.serials objectAtIndex:indexPath.row];
    BOOL isSelected = [self indexOfSelectedSerial:postSerial] >= 0;
    if (!isSelected) {
        [self selectSerial:postSerial];
        [self.tableView reloadData];
    }
//    if (isSelected) {
//        [self deselectSerial:postSerial];
//    }
    
}
#pragma mark - BKScrollViewDragRefreshDelegate
- (void)scrollViewWillBeginLoadingMore:(id)scrollView{
    [self search:self.serials.count];
}
#pragma mark - UScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.tableView scrollViewDidScroll];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    [self.tableView scrollViewDidEndDragging];
}
#pragma mark - SerialSearchDelegate
- (void)serialSearchViewController:(id)searchViewController didSelectSerial:(PostSerial *)serial{
    if(!serial.id){
        //创建serial
        SerialEditViewController *vc = [[SerialEditViewController alloc] init];
        vc.delegate = self;
        vc.postSerial = serial;
        vc.modalPresentationStyle = UIModalPresentationFullScreen;
        [self.navigationController presentViewController:vc animated:YES completion:nil];
        return;
    }
    
    [self.searchController setActive:NO];
    [self selectSerial:serial];
//    if(self.delegate && [self.delegate respondsToSelector:@selector(serialSearchViewController:didSelectSerial:)]){
//        [self.delegate serialSearchViewController:self didSelectSerial:serial];
//    }
//    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)serialEditViewController:(SerialEditViewController *)vc didCreateSerial:(PostSerial *)postSerial{
    [self.searchResultsController.tableView reloadData];
    [vc dismissViewControllerAnimated:YES completion:nil];
}
- (BOOL)serialEditViewControllerShouldQuit:(SerialEditViewController *)vc{
    [vc dismissViewControllerAnimated:YES completion:nil];
    return NO;
}

#pragma mark - multi selection
- (void)deselect:(UIButton*)btn{
    
    NSInteger i = [self.selectedButtons indexOfObject:btn];
    [self.selectedButtons removeObjectAtIndex:i];
    [self.selectedItems removeObjectAtIndex:i];
    [btn removeFromSuperview];
    [self layoutSubViews];
    
    [self.tableView reloadData];
}
- (void)addButtonForSerial:(PostSerial *)serial{
    
    CGSize buttonSize = [serial.title sizeWithAttributes:@{NSFontAttributeName:THEME_TAG_BTN_TITLE_FONT}];
    CGRect itemFrame = CGRectMake(0, 0, buttonSize.width+20, buttonSize.height + 4);
    itemFrame.origin = self.view.center;
    
    UIButton *btn = [[UIButton alloc] initWithFrame:itemFrame];
    [btn setTitle:serial.title forState:UIControlStateNormal];
    btn.titleLabel.font = THEME_TAG_BTN_TITLE_FONT;
    [btn setTitleColor:THEME_TAG_BTN_TITLE_COLOR forState:UIControlStateNormal];
    btn.backgroundColor = THEME_TAG_BTN_BG_COLOR;
    btn.clipsToBounds = YES;
    btn.layer.cornerRadius = itemFrame.size.height/2;
    btn.layer.borderWidth = 1.0f;
    btn.layer.borderColor = [THEME_TAG_BTN_BORDER_COLOR CGColor];
    [btn addTarget:self action:@selector(deselect:) forControlEvents:UIControlEventTouchUpInside];
    [self.topView addSubview:btn];
    [self.selectedButtons addObject:btn];
    [self layoutSubViews];
}
- (BOOL)selectSerial:(PostSerial*)serial{
    if (self.selectedItems.count >= self.maxSelectedCount) {
        [BKIndicator showTips:[NSString stringWithFormat:NSLocalizedString(@"max_selected_serial_count_format", @"提醒"), self.maxSelectedCount]
                     duration:2.0f
                   completion:nil];
        return NO;
    }
    NSInteger i = [self indexOfSelectedSerial:serial];
    if (i >= 0) {
        UIButton *btn = [self.selectedButtons objectAtIndex:i];
        [UIView animateWithDuration:0.2
                         animations:^{
                             btn.transform = CGAffineTransformMakeScale(1.2,1.2);
                         }
                         completion:^(BOOL finished) {
                             btn.transform = CGAffineTransformIdentity;
                         }];
        return NO;
    }
    
    [self.selectedItems addObject:serial];
    [self addButtonForSerial:serial];
    [self.tableView reloadData];
    return YES;
}
- (void)layoutSubViews{
    CGFloat topViewHeight = 0;
    
    //topView: 计算topView 高度
    CGFloat topViewPadding = 10;
    CGRect itemFrame = CGRectMake(topViewPadding, topViewPadding, 0, 0);
    for (NSInteger i = 0; i<self.selectedButtons.count; i++) {
        UIButton *btn = [self.selectedButtons objectAtIndex:i];
        itemFrame.size = btn.frame.size;
        itemFrame.size.width = MIN(self.view.bounds.size.width - 2* topViewPadding, itemFrame.size.width);
        if ((itemFrame.origin.x + itemFrame.size.width) >= self.view.bounds.size.width) {
            itemFrame.origin.y += itemFrame.size.height+5;
            itemFrame.origin.x = topViewPadding;
        }
        [UIView animateWithDuration:0.1 animations:^{
            btn.frame = itemFrame;
        }];
        
        itemFrame.origin.x += itemFrame.size.width+10;
    }
    if (self.selectedButtons.count > 0) {
        topViewHeight = itemFrame.origin.y + itemFrame.size.height + topViewPadding;
    }
    
    //end topView
    
    NSLayoutConstraint *topViewHeightConstraint = [self.topView constraintForAttribute:NSLayoutAttributeHeight firstItem:self.topView secondItem:nil];
    topViewHeightConstraint.constant = topViewHeight;
}
@end
